package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.util.Map;


/**
 * 公众平台通用接口工具类
 * 
 * @author Administrator
 * 
 */
public class WeiXinUtil {
	private static Logger log = LoggerFactory.getLogger(WeiXinUtil.class);
	// 获取access_token的接口地址（GET） 限200（次/天）
	public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

	/**
	 * 发起https请求并获取结果
	 *
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static String httpRequest(String requestUrl,
										 String requestMethod, String outputStr) {
		String jsonObject = null;
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			 if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect();


			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			// 释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			System.out.println(buffer.toString());
			jsonObject = buffer.toString();
		} catch (ConnectException ce) {
			log.error("连接超时：{}", ce);
		} catch (Exception e) {
			log.error("https 请求异常:{}", e);
		}
		return jsonObject;
	}

	/**
	 * 获取access_token
	 * 
	 * @param appid
	 *            凭证
	 * @param appsecret
	 *            密钥
	 * @return
	 */
	public static AccessToken getAccessToken(String appid, String appsecret) {
		AccessToken accessToken = null;

		String requestUrl = token_url.replace("APPID", appid).replace(
				"APPSECRET", appsecret);
		// 发送GET请求获取凭证
		String jsonObject = httpRequest(requestUrl, "GET", null);
		Map<String, Object> map = JSON.parseObject(jsonObject, new TypeReference<Map<String, Object>>() {});
		// 如果请求成功
		if (null != jsonObject) {
			//try {
				accessToken = new AccessToken();
				accessToken
						.setAccessToken(map.get("access_token").toString());
				accessToken.setExpiresIn(Integer.valueOf(map.get("expires_in").toString()));
			//} catch (JSONException e) {
			/*	accessToken = null;
				// 获取token失败
				log.error("获取token失败 errcode:{} errmsg:{}",
						jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));*/
		//	}
		}
		return accessToken;
	}

	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 根据内容类型判断文件扩展名
	 * 
	 * @param contentType
	 *            内容类型
	 * @return
	 */
	public static String getFileExt(String contentType) {
		String fileExt = "";
		if ("image/jpeg".equals(contentType))
			fileExt = ".jpg";
		else if ("audio/mpeg".equals(contentType))
			fileExt = ".mp3";
		else if ("audio/amr".equals(contentType))
			fileExt = ".amr";
		else if ("video/mp4".equals(contentType))
			fileExt = ".mp4";
		else if ("video/mpeg4".equals(contentType))
			fileExt = ".mp4";
		return fileExt;
	}
	
	/***
	 * 获取用户基本信息
	 * 根据openId和accessToken获取用户的基本信息(包括用户姓名、性别、昵称)
	 * @param openId
	 * @return 用户的基本信息 json 格式数据
	 * **/
//	public static JSONObject getUserInfo(String openId,String accessToken){
//		//微信获取用户信息Url地址
//		 String userInfoUrl="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
//         //最终地址（包括传递参数）
//		 //发送请求，并接收请求返回结果
//         JSONObject jsonObject = httpRequest(userInfoUrl,"POST",null);
//
//		return jsonObject;
//	}
	/***20
	 * 获取用户基本信息
	 * 根据appid/appSecret和code获取openId和accessToken
	 * @param appid/appSecret/code
	 * @return  json 格式数据
	 * **/
	public static String getOpenToken(String appid,String appSecret,String code){
		String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
		String jsonObject = httpRequest(url,"POST",null);
		Map<String, Object> map = JSON.parseObject(jsonObject, new TypeReference<Map<String, Object>>() {});
		return map.get("access_token").toString();
	}
	
	
	/***
	 * 根据accessToken获取jsapi_ticket
	 * @param accessToken
	 * @return  json 格式数据
	 * */
	public static String getJsapiTicket(String accessToken){
		String url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
		String jsonObject =null;
		jsonObject = httpRequest(url,"POST",null).toString();
		Map<String, Object> map = JSON.parseObject(jsonObject, new TypeReference<Map<String, Object>>() {});
		return map.get("ticket").toString();
	}

	/***
	 * 根据accessToken获取template_id
	 * @param accessToken
	 * @return  String 格式数据
	 * */
//	public static String getTemplate_id(String accessToken){
//		String url="https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token="+accessToken;
//		JSONObject jsonObject =null;
//		jsonObject = httpRequest(url,"POST",null);
//		if(EmptyUtils.isNotEmpty(jsonObject)){
//			return jsonObject.get("template_id").toString();
//		}else{
//			return  "";
//		}
//	}
}
